<?php

include_once 'autoload.php';

class FormLogin extends Zend_Form {

    public function init() {
        $this->setName('Login');
        $username = new Zend_Form_Element_Text('username');
        $username->setLabel('Username: ')
                ->setRequired();
        //Création d’un validateur de mot de passe complexe basé sur les regex 
        $pswRegex = new Zend_Validate_Regex('((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20})');
        $pswRegex->setMessage("6 a 20 caracteres, au moins 1 chiffre, au moins une majuscule");
        $psw = new Zend_Form_Element_Password('password');
        $psw->setLabel('Mot de passe:')
                ->addValidator($pswRegex)
                ->setRequired();
        $login = new Zend_Form_Element_Submit('login');
        $login->setLabel('Envoyer');
        $this->addElements(array($username, $psw, $login))
                ->setMethod('post')
                ->setAction('formAuth02.php');
    }

}

function estAuthentifie($username, $psw) {
    $db = new Zend_Db_Adapter_Pdo_Mysql(array(
        'host' => 'localhost',
        'username' => 'root',
        'password' => '',
        'dbname' => 'gsb_frais_v1'
    ));

    $authAdapter = new Zend_Auth_Adapter_DbTable($db);
    $authAdapter->setTableName('visiteur')
            ->setIdentityColumn('login')
            ->setCredentialColumn('mdp')
    ;
    $authAdapter->setIdentity($username)
            ->setCredential($psw);
    $auth = Zend_Auth::getInstance();
    $result = $auth->authenticate($authAdapter);
    return ($result->isValid() ? TRUE : FALSE);
}

$view = new Zend_View(); //autoload 
$form = new FormLogin(); //autoload 
if (!$_POST) {
// rendu du formulaire vierge 
    echo $form->render($view);
} else
if (!$form->isValid($_POST)) {
// rendu du formulaire rempli et messages d'erreurs 
    echo $form->render($view);
} else {
// formulaire valide.traiter les donnees postees 
    //Zend_Debug::dump($_POST); idem var_dump($_POST) 
    //Zend_Debug::dump($form->getValues());
    $username = $form->getValue('username');
    $psw = $form->getValue('password');
    if (estAuthentifie($username, $psw)) {
        echo 'true';
    } else {
        echo 'false';
    }
}
?>